//
//  AVDMeetingVC.m
//  AVD_Demo
//
//  Created by 3tee on 2022/11/16.
//

#import "AVDMeetingVC.h"
#import "AVDBottomTabTool.h"
#import "AVDTopBarTool.h"
#import "AVDRendersView.h"
#import "AVDUsersVC.h"
#import "AVDChatVC.h"




@interface AVDMeetingVC ()<AVDVideoDelegate,AVDScreenDelegate,AVDRoomDelegate,AVDWhiteboardDelegate>

@property (nonatomic, weak)AVDBottomTabTool *botBar;/**底部Bar*/
@property (nonatomic, weak)AVDTopBarTool *topBar;/**顶部Bar*/
@property (nonatomic, weak)AVDRendersView *rendersVie;/**视频渲染窗口父视图*/

@property (nonatomic, strong)AVDRoom *mRoom;/**房间模块*/
@property (nonatomic, strong)AVDVideo *mVideo;/**视频模块*/
@property (nonatomic, strong)AVDAudio *mAudio;/**音频模块*/
@property (nonatomic, strong)AVDScreen *mScreen;/**屏幕共享模块*/
@property (nonatomic, strong)AVDWhiteboard *mboard;/**白板模块*/
@property (nonatomic, strong)AVDCanvasView *canvasView;/**白板渲染*/
@property (nonatomic, strong)AVDWhiteboardInfo *info;/**白板信息*/

@end

@implementation AVDMeetingVC

- (void)dealloc{
    NSLog(@"AVDMeetingVC dealloc");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupUI];
    [self configAVD];
    NSLog(@"11111");
}

#pragma mark 配置需要使用到的模块
- (void)configAVD{
    NSString *roomid = [[NSUserDefaults standardUserDefaults] stringForKey:roomIdKey];
    self.mRoom = [AVDRoom obtain:roomid];
    self.mRoom.delegate = self;
    self.mAudio = [AVDAudio getAudio:self.mRoom];
    self.mVideo = [AVDVideo getVideo:self.mRoom];
    self.mVideo.delegate = self;
    self.mScreen = [AVDScreen getScreen:self.mRoom];
    self.mScreen.delegate = self;
    self.mboard = [AVDWhiteboard getWhiteboard:self.mRoom];
    self.mboard.delegate = self;
    if([[NSUserDefaults standardUserDefaults] boolForKey:micKey]){
        [self.mAudio openMicrophone];
    }
    if([[NSUserDefaults standardUserDefaults] boolForKey:camKey]){
        [self.mVideo publishLocalCamera];
    }
    [self.mVideo.publishedCameras enumerateObjectsUsingBlock:^(AVDCamera *camer, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.mVideo subscribe:camer.id];
        [self.mVideo attachRenderWithDeviceId:camer.id render:[self.rendersVie getFreeRender]];
    }];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
   
}


#pragma mark 界面UI
- (void)setupUI{
    //底部工具条
    AVDBottomTabTool *botBar = [[AVDBottomTabTool alloc]initWithFrame:CGRectMake(0, SCREENH_HEIGHT -60 , SCREEN_WIDTH, 60)];
//    NSLog(@"w = %f", CGRectGetWidth(self.view.frame));
    [self.view addSubview:botBar];
    self.botBar = botBar;
    
    //顶部工具条
    AVDTopBarTool *topBar = [[AVDTopBarTool alloc]initWithFrame:CGRectMake(0, k_Height_StatusBar, SCREEN_WIDTH, 44)];
    [topBar updateRoomId:[[NSUserDefaults standardUserDefaults] stringForKey:roomIdKey]];
    @WeakObj(self);
    topBar.leaveBlock = ^{
        @StrongObj(self);
        [self.mRoom leave:AVD_Success];
        [self.mRoom destory];
        [self.navigationController popViewControllerAnimated:YES];
    };
    
    topBar.speakerBlock = ^(BOOL isSelect) {
        @StrongObj(self);
        [self.mAudio setSpeakerMode:isSelect?SM_Handfree:SM_Receiver];
    };
    [self.view addSubview:topBar];
    self.topBar = topBar;
    
    //中间视频展示区域
    AVDRendersView *rendersV = [[AVDRendersView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(topBar.frame), SCREEN_WIDTH, CGRectGetMinY(botBar.frame)-CGRectGetMaxY(topBar.frame))];
    [self.view addSubview:rendersV];
    self.rendersVie = rendersV;
    
    //白板渲染视图
    self.canvasView = [[AVDCanvasView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.rendersVie.frame), CGRectGetHeight(self.rendersVie.frame))];
    self.canvasView.hidden = YES;
    [self.rendersVie addSubview:self.canvasView];
    
    botBar.micBlock = ^(BOOL isSelect) {
        @StrongObj(self);
        if(isSelect){
            [self.mAudio openMicrophone];
        }else{
            [self.mAudio closeMicrophone];
        }
    };
    
    botBar.camBlock = ^(BOOL isSelect) {
        @StrongObj(self);
        if(isSelect){
            [self.mVideo publishLocalCamera];
        }else{
            [self.mVideo unpublishLocalCamera];
        }
    };
    
    botBar.swithBlock = ^(BOOL isSelect) {
        @StrongObj(self);
        //[rendersV updateLayoutRender:3];
        [self.mVideo switchToLocalCamera];
    };
    
    botBar.boardBlock = ^(BOOL isSelect) {
        @StrongObj(self);
        if(isSelect){
            AVDWhiteboardInfo *info = [[AVDWhiteboardInfo alloc]init];
            info.boardId = [[NSUUID UUID] UUIDString];
            info.userId = [self.mboard.usermanager getSelfUserId];
            info.width = CGRectGetWidth(self.canvasView.frame);
            info.height = CGRectGetHeight(self.canvasView.frame);
            info.color = [UIColor whiteColor];
            self.info = info;
            [self.mboard createBoard:info];
            self.canvasView.hidden = NO;
            [self.mboard attachView:self.canvasView boardInfo:info];
            AVDResult result = [self.mboard shareBoard:info.boardId];
        }else{
            [self.mboard closeBoard:self.info.boardId];
            [self.mboard dettachView:self.canvasView boardId:self.info.boardId];
            self.canvasView.hidden = YES;
        }
    };
    
    botBar.screenBlock = ^(BOOL isSelect) {
        @StrongObj(self);
        NSLog(@"screen block run");
        if(isSelect){
            [self.mScreen publishScreen:screen_resolution_720p fps:15];
        }else{
            [self.mScreen unpublishScreen];
        }
    };
    
    botBar.usersBlock = ^{
        @StrongObj(self);
        [self.navigationController pushViewController:[AVDUsersVC new] animated:YES];
    };
    
    botBar.chatBlock = ^{
        @StrongObj(self);
        [self.navigationController pushViewController:[AVDChatVC new] animated:YES];
    };
    
}

#pragma mark AVDVideoDelegate
- (void)onPublishLocalResult:(AVDResult)result deviceId:(AVDDeviceId)fromId{
    [self.mVideo attachRenderWithDeviceId:fromId render:[self.rendersVie getFreeRender]];
    
}

- (void)onUnpublishLocalResult:(AVDResult)result deviceId:(AVDDeviceId)fromId{
    
}

- (void)onPublishCameraNotify:(AVDCamera *)camera{
    if([self.mVideo isSelfDevice:camera.id]){
        return;
    }
    [self.mVideo subscribe:camera.id];
    AVDVideoView *render = [self.rendersVie getFreeRender];
    [render setVideoId:camera.id];
    [self.mVideo attachRenderWithDeviceId:camera.id render:render];
    //[self.rendersVie updateLayoutRender:2];
}

- (void)onUnpublishCameraNotify:(AVDCamera *)camera{
    AVDVideoView *render = [self.rendersVie getRenderWithDeviceId:camera.id];
    [self.mVideo unsubscribe:camera.id];
    [self.mVideo detachRenderWithRender:render];
    [render setVideoId:@""];
    //[self.rendersVie updateLayoutRender:1];

}



#pragma mark AVDAudioDelegate

#pragma mark AVDScreenDelegate
- (void)onPublishScreenNotify:(AVDVideoDevice *)screen{
    if([self.mScreen isSelfDevice:screen.id]){
        return;
    }
    [self.mScreen subscribe:screen.id];
    [self.mScreen attachRenderWithDeviceId:screen.id render:[self.rendersVie getFreeRender]];
}

- (void)onUnpublishScreenNotify:(AVDVideoDevice *)screen{
    AVDVideoView *render = [self.rendersVie getRenderWithDeviceId:screen.id];
    [self.mScreen unsubscribe:screen.id];
    [self.mScreen detachRenderWithRender:render];
}


#pragma mark 订阅相关
- (void)onSubscribeResult:(AVDResult)result deviceId:(AVDDeviceId)fromId{
    
}

- (void)onUnsubscribeResult:(AVDResult)result deviceId:(AVDDeviceId)fromId{
    
}

#pragma mark 断线重连
- (void)onConnectionStatus:(enum AVDConnectionStatus)status{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    NSLog(@"xxxxstatus = %d",status);
    if(status == connecting){
        hud.label.text = @"断线重连中。。。";
        [hud hideAnimated:YES afterDelay:0.5f];
    }else if (status == connected){
        hud.label.text = @"重连成功";
        [hud hideAnimated:YES afterDelay:0.5f];
    }else if(status == connectFailed){
        hud.label.text = @"重连失败";
        [hud hideAnimated:YES afterDelay:0.5f];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [hud hideAnimated:YES afterDelay:0.5f];

    }
  
    
}

#pragma  mark 自己或者别人离会回调
- (void)onLeaveIndication:(AVDResult)reason fromUser:(AVDUserId)fromId{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    if(reason == 807){
        hud.label.text = @"udp不通，请检查udp端口";
        [hud hideAnimated:YES afterDelay:2.f];
        [self.mRoom destory];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

#pragma mark 白板回调
- (void)onShareBoardNotify:(AVDWhiteboardInfo *)whiteboardInfo{
    NSLog(@"shard info = %@ h = %f",whiteboardInfo,SCREENH_HEIGHT);
    self.canvasView.hidden = NO;
    [self.mboard attachView:self.canvasView boardInfo:whiteboardInfo];
}

- (void)onCloseBoardNotify:(AVDBoardId)whiteboardId{
    NSLog(@"onCloseBoardNotify");
    [self.mboard dettachView:self.canvasView boardId:whiteboardId];
    self.canvasView.hidden = YES;
}





@end
